package cool.houge.pig.infra.service;

import cool.houge.pig.BizCodeException;
import cool.houge.pig.BizErrors;
import cool.houge.pig.model.Sequence;
import cool.houge.pig.repository.SequenceRepository;
import cool.houge.pig.service.SharedSequenceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Mono;

/** @author KK (kzou227@qq.com) */
@Service
public class SequenceServiceImpl implements SharedSequenceService {

  private static final String TOKEN_SEQ_NAME = "token.seq";

  private final SequenceRepository sequenceRepository;

  public SequenceServiceImpl(SequenceRepository sequenceRepository) {
    this.sequenceRepository = sequenceRepository;
  }

  @Transactional
  @Override
  public Mono<Long> nextTokenSeq() {
    return nextSeq(TOKEN_SEQ_NAME);
  }

  Mono<Long> nextSeq(String name) {
    return sequenceRepository
        .increment(name)
        .flatMap(
            b -> {
              if (b) {
                return sequenceRepository.findById(name);
              }
              return Mono.error(new BizCodeException(BizErrors.C707));
            })
        .map(Sequence::getCurrentValue);
  }
}
